package me.zhengjie.modules.website.service.impl;

import me.zhengjie.modules.website.domain.ReservationDetailTable;
import me.zhengjie.modules.website.repository.ReservationDetailTableRepository;
import me.zhengjie.modules.website.repository.ReservationDetailTableSpecifications;
import me.zhengjie.modules.website.service.ReservationDetailTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import me.zhengjie.modules.website.domain.PageResult;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author system
 * @since 2024-10-23 22:22:57
 */
@Service
public class ReservationDetailTableServiceImpl implements ReservationDetailTableService {

    @Autowired
    private ReservationDetailTableRepository reservationDetailTableRepository;


   /* @Override
    public PageResult<ReservationDetailTable> findPage(ReservationDetailTable reservationDetailTable, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
        Page<ReservationDetailTable> page = reservationDetailTableRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 通过反射遍历 ReservationDetailTable 的所有字段，过滤静态字段
            for (Field field : ReservationDetailTable.class.getDeclaredFields()) {
                field.setAccessible(true); // 允许访问私有字段

                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                try {
                    Object value = field.get(reservationDetailTable); // 获取字段值
                    if (value != null) { // 如果字段不为空，添加查询条件
                        predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 时间范围条件
            if (startDate != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(startDate)));
            }
            if (endDate != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(endDate)));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);

        PageResult<ReservationDetailTable> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }*/

    @Override
    public PageResult<ReservationDetailTable> findPage(ReservationDetailTable reservationDetailTable, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
        Page<ReservationDetailTable> page = reservationDetailTableRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 通过反射遍历 ReservationDetailTable 的所有字段，过滤静态字段
            for (Field field : ReservationDetailTable.class.getDeclaredFields()) {
                field.setAccessible(true); // 允许访问私有字段

                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                try {
                    Object value = field.get(reservationDetailTable); // 获取字段值
                    if (value != null) { // 如果字段不为空，添加查询条件
                        predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 时间范围条件
            if (startDate != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("reservationTime"), Timestamp.valueOf(startDate)));
            }
            if (endDate != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("reservationTime"), Timestamp.valueOf(endDate)));
            }

            // 设置排序条件：根据预约时间排序，时间越近越靠前
            query.orderBy(criteriaBuilder.desc(root.get("reservationTime")));  // 降序排序，时间越近越靠前

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);

        // 组装分页结果
        PageResult<ReservationDetailTable> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }



    @Override
    public PageResult<ReservationDetailTable> findPage(ReservationDetailTable reservationDetailTable, Pageable pageable) {
        Page<ReservationDetailTable> page = reservationDetailTableRepository.findAll(ReservationDetailTableSpecifications.queryList(reservationDetailTable), pageable);
        PageResult<ReservationDetailTable> result = new PageResult();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }

    @Override
    public List<ReservationDetailTable> findList(ReservationDetailTable reservationDetailTable) {
        return reservationDetailTableRepository.findAll(ReservationDetailTableSpecifications.queryList(reservationDetailTable));
    }

    @Override
    public ReservationDetailTable findById(Long id) {
        return reservationDetailTableRepository.findById(id).orElse(null);
    }

    @Override
    public ReservationDetailTable insert(ReservationDetailTable reservationDetailTable) {
        return reservationDetailTableRepository.save(reservationDetailTable);
    }

    @Override
    public ReservationDetailTable update(ReservationDetailTable reservationDetailTable) {
        return reservationDetailTableRepository.saveAndFlush(reservationDetailTable);
    }

    @Override
    public void delete(Long id) {
        reservationDetailTableRepository.deleteById(id);
    }

    /**
     * 根据预约访客表ID查询所有预约详情，并按预约时间排序（分页）
     *
     * @param reservationId 预约访客表ID
     * @param pageable 分页参数
     * @return Page<ReservationDetailTable> 分页结果
     */
    @Override
    public Page<ReservationDetailTable> findReservationDetailsByReservationId(Integer reservationId, Pageable pageable) {
        return reservationDetailTableRepository.findByReservationIdOrderByReservationTimeAsc(reservationId, pageable);
    }

    /**
     * 审批预约详情
     *
     * @param id          预约详情的 ID
     * @param reviewNotes 审批意见
     */
    @Transactional
    @Override
    public void approveReservationDetail(Long id, Boolean reviewNotes, String responseContent) {
        // 查询预约详情
        ReservationDetailTable reservationDetail = reservationDetailTableRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("预约详情不存在，ID: " + id));

        if (reviewNotes){
            reservationDetail.setReviewStatus("通过"); // 设置审批状态
            reservationDetail.setIsApproved(true);
        }else {
            reservationDetail.setReviewStatus("驳回"); // 设置审批状态
            reservationDetail.setResponseContent(responseContent);
            reservationDetail.setIsApproved(false);
        }

        // 保存更新
        reservationDetailTableRepository.save(reservationDetail);
    }

}